package com.banquanhu.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Test {

	public static void main(String[] args) throws Exception {

		if (args.length < 2) {
			System.out.println("参数输入有误，请-h查看说明");
		}
		for (int argc = 0; argc < args.length; argc++) {
			final String arg = args[argc];
			if (arg.equals("-unzip")) {
				unzip(args[++argc], args[++argc]);
			} else if (arg.equals("-zip")) {
				zip(args[++argc], args[++argc]);
			} else if (arg.equals("-h")) {
				System.out.println("-unzip apk路径 输出文件夹\n-zip apk路径 输出apk");
			} else {
				System.out.println("参数输入有误，请-h查看说明");
			}
		}

	}

	private static void zip(String path, String apk) throws Exception {
		File file = new File(apk);
		if (file.getParentFile() != null && !file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		FileOutputStream fos = new FileOutputStream(apk);
		TinySign.sign(new File(path), file, fos);
	}

	private static void unzip(String apk, String path) throws FileNotFoundException, IOException {
		new File(path).mkdirs();
		FileInputStream input = new FileInputStream(apk);
		ZipInputStream zis = new ZipInputStream(input);
		for (ZipEntry e = zis.getNextEntry(); e != null; e = zis.getNextEntry()) {
			String name = e.getName();
			if (!e.isDirectory()) {
				File file = new File(path, name);
				file.getParentFile().mkdirs();
				FileOutputStream fos = new FileOutputStream(file);
				StreamUtils.write(zis, fos);
				fos.close();
			}
		}
		zis.close();
	}

}
